using FileManager.Models;
using FileManager.Services;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace FileManager.ViewModels
{
    public class ImageViewerViewModel : BaseViewModel
    {
        private FileItem _currentFile;
        private BitmapImage _currentImage;
        private double _zoomFactor;
        private double _rotationAngle;
        private string _statusMessage;
        
        public ImageViewerViewModel(FileItem file, ImageSource image)
        {
            CurrentFile = file;
            CurrentImage = image as BitmapImage;
            
            ZoomFactor = 1.0;
            RotationAngle = 0;
            
            // 初始化命令
            ZoomInCommand = new RelayCommand((p) => ZoomFactor += 0.1);
            ZoomOutCommand = new RelayCommand((p) => ZoomFactor = Math.Max(0.1, ZoomFactor - 0.1));
            RotateLeftCommand = new RelayCommand((p) => RotationAngle = (RotationAngle - 90) % 360);
            RotateRightCommand = new RelayCommand((p) => RotationAngle = (RotationAngle + 90) % 360);
            SaveAsCommand = new RelayCommand((p) => SaveImageAsAsync(p as string));
        }
        
        public FileItem CurrentFile
        {
            get => _currentFile;
            set
            {
                if (SetProperty(ref _currentFile, value))
                {
                    // 这里不需要await，因为我们不希望阻塞UI线程
                    _ = LoadImageAsync(value);
                }
            }
        }
        
        public BitmapImage CurrentImage
        {
            get => _currentImage;
            set => SetProperty(ref _currentImage, value);
        }
        
        public double ZoomFactor
        {
            get => _zoomFactor;
            set => SetProperty(ref _zoomFactor, value);
        }
        
        public double RotationAngle
        {
            get => _rotationAngle;
            set => SetProperty(ref _rotationAngle, value);
        }
        
        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }
        
        public ICommand ZoomInCommand { get; }
        public ICommand ZoomOutCommand { get; }
        public ICommand RotateLeftCommand { get; }
        public ICommand RotateRightCommand { get; }
        public ICommand SaveAsCommand { get; }
        
        private async Task LoadImageAsync(FileItem file)
        {
            try
            {
                StatusMessage = "正在加载图片...";
                
                // 使用Task.Run将IO操作放在后台线程
                await Task.Run(() =>
                {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.UriSource = new Uri(file.FilePath);
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.EndInit();
                    image.Freeze(); // 冻结对象以便在UI线程使用
                    
                    // 在UI线程更新CurrentImage
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        CurrentImage = image;
                    });
                });
                
                StatusMessage = "图片加载完成";
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载图片失败: {ex.Message}";
            }
        }

        private async Task SaveImageAsAsync(string path)
        {
            if (CurrentFile == null || CurrentImage == null)
                return;
            
            try
            {
                StatusMessage = "正在保存图片...";
                
                // 移除嵌套的async lambda
                await Task.Run(() =>
                {
                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        BitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(CurrentImage));
                        encoder.Save(fileStream);
                    }
                });
                
                StatusMessage = "图片保存成功";
            }
            catch (Exception ex)
            {
                StatusMessage = $"保存图片失败: {ex.Message}";
            }
        }
    }
}